<template>
  <div>
    <div class="planManage-main">
      <div class="btn-content">
        <img
          v-for="(item, index) of btnContentData"
          :key="index"
          class="btn-content-img"
          :src="item.currentImg"
          :title="item.title"
          @click="btnClick(index)"
        />
      </div>
      <transition name="slide-fade">
        <div v-if="btnContentData[0].activated" class="plan-main">
          <div class="plan-main-title">
            <img class="shrink-btn" src="/images/shrink.png" alt="" @click="btnClick(0)" />
            <div class="title">飞行计划筛选</div>
            <div class="separator"></div>
          </div>
          <div v-if="checkPlanData.startTime && checkPlanData.endTime" class="current-time">
            <div class="current-time-title">当前所选计划的起止时间</div>
            <div>{{ checkPlanData.startTime }} 至 {{ checkPlanData.endTime }}</div>
          </div>
          <div class="querySearch">
            <el-date-picker v-model="startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择起始时间"> </el-date-picker>
            <el-date-picker v-model="endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择结束时间"> </el-date-picker>
            <el-button class="search-btn" type="primary" size="medium" @click="searchFun">搜索</el-button>
          </div>
          <div class="plan-main-table">
            <el-table ref="multipleTable" :data="tableData" style="width: 100%" @row-dblclick="dblClick" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="id" label="计划编号" align="center" header-align="center"> </el-table-column>
              <el-table-column prop="taskNature" label="任务性质" align="center" header-align="center"> </el-table-column>
              <el-table-column prop="startTime" label="起始时间" align="center" header-align="center"> </el-table-column>
              <el-table-column prop="takeoffAirport" label="起飞机场" align="center" header-align="center"> </el-table-column>
              <el-table-column prop="endTime" label="结束时间" align="center" header-align="center"> </el-table-column>
              <el-table-column prop="landAirport" label="降落机场" align="center" header-align="center"> </el-table-column>
            </el-table>
          </div>
          <el-button class="remove-btn" type="danger" size="medium" @click="removeTargetPath">清除已选计划</el-button>
          <el-button class="render-btn" type="primary" size="medium" @click="renderLinesClick">加载已选计划</el-button>
        </div>
      </transition>
      <img class="btn" src="/images/clock.png" alt="" title="返回计划所在时间" @click="setTimeLine" />
    </div>
    <conflict-view></conflict-view>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { flightPlainPost } from '@/api/planHome'
import ConflictView from './ConflictView'
export default {
  name: 'PlanManage',
  components: {
    ConflictView
  },
  data() {
    return {
      btnContentData: [
        {
          currentImg: '/images/right-icon5.png',
          imgsrc: '/images/right-icon5.png',
          activatedImgsrc: '/images/right-icon5-activated.png',
          title: '飞行计划',
          activated: false
        }
      ],
      startTime: '',
      endTime: '',
      tableData: [],
      checkPlanData: {},
      multipleSelection: []
    }
  },
  mounted() {
    this.addStorageListener()
    this.addPlayRealtimeLister()
  },
  methods: {
    btnClick(index) {
      this.btnContentData[index].activated = !this.btnContentData[index].activated
      if (this.btnContentData[index].activated) {
        this.btnContentData[index].currentImg = this.btnContentData[index].activatedImgsrc
      } else {
        this.btnContentData[index].currentImg = this.btnContentData[index].imgsrc
      }
    },
    async searchFun() {
      const param = {
        apprStatus: 1,
        callSign: '',
        endTime: this.endTime,
        id: '',
        startTime: this.startTime,
        taskNature: this.taskNature
      }
      const res = await flightPlainPost(1, '', param)
      this.tableData = res.data.data
    },
    dblClick(row) {
      console.log(row)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    renderLinesClick() {
      this.removeTargetPath()
      if (this.multipleSelection.length > 0) {
        this.loadTargetPath(this.multipleSelection)
      }
    },
    // 添加storage监听
    addStorageListener() {
      const that = this
      window.addEventListener('storage', function(e) {
        if (e.key === 'checkedPlan') {
          that.checkPlanData = JSON.parse(e.newValue)
          console.log(that.checkPlanData)
          // that.removeCheckedLine()
          that.addCheckedLine(that.checkPlanData)
        }
      })
    },
    // 渲染计划页所点击数据
    addCheckedLine(param) {
      if (!param.rangeHeight) {
        Message({
          message: '所选计划暂无航线数据',
          type: 'error',
          duration: 2000
        })
      } else {
        // if (!this.$earth.airTargetHistory) {
        //   this.$earth.airTargetHistory = new GV.TargetHistory(this.$earth.viewer)
        //   this.$earth.airTargetHistory.smoothTrack = true
        // }

        this.$earth.planAirTargetHistory = new GV.TargetHistory(this.$earth.viewer)
        this.$earth.planAirTargetHistory.smoothTrack = true
        this.$earth.planAirTargetHistory.removeAll()

        const lineData = JSON.parse(param.rangeHeight)
        const airLineTime = new Date(param.startTime).getTime()
        // 暂时设置每个时间点为startTime + 1分钟
        lineData.forEach((innerItem, i) => {
          innerItem.push(airLineTime + i * 60 * 1000)
        })
        const id = `reviewd_plan_${param.id}`
        const tTarget = new GV.TargetItem(id, lineData[0][0], lineData[0][1], lineData[0][2], 0)
        tTarget.name = id
        tTarget.angle = Math.random() * 360
        const style = tTarget.style
        style.pointDisplayConditionn = new Cesium.DistanceDisplayCondition(60000000)
        style.labelDisplayCondition = new Cesium.DistanceDisplayCondition(6000, 600000)
        style.iconDisplayCondition = new Cesium.DistanceDisplayCondition(60000, 60000000)
        style.modelDisplayCondition = new Cesium.DistanceDisplayCondition(0, 600000)
        style.labeloffsetx = 10
        style.labeloffsety = -20
        style.iconSize = 32
        style.modelUrl = '/data/model/Cesium_Air.glb'
        style.iconUrl = '/data/model/003.png'
        style.color = 'white'
        this.$earth.planAirTargetHistory.addTargetHistory(tTarget, lineData)

        const startTime = new Date(airLineTime)
        const endTime = new Date(airLineTime + 60 * 60 * 1000)
        this.$earth.planAirTargetHistory.setTimeSection(startTime, endTime)
        this.$earth.planAirTargetHistory.pointSize = 0
        this.$earth.planAirTargetHistory.lineColor = Cesium.Color.YELLOW

        Cesium.JulianDate.fromDate(startTime)

        // const cTime = new Date(param.startTime)
        // const cJulianDate = new Cesium.JulianDate()
        // Cesium.JulianDate.fromDate(cTime, cJulianDate)
        // this.$earth.viewer.clock.currentTime = Cesium.JulianDate.fromDate(cTime, cJulianDate)
      }
    },
    // 移除计划页所点击数据
    removeCheckedLine() {
      if (this.$earth.planAirTargetHistory) {
        this.$earth.planAirTargetHistory.removeAll()
      }
    },
    // 监听点击Animation 左侧当前时间按钮，设置时间轴刻度缩放， 使用 setTimeout 使之在下一次事件循环中 来设置时间刻度，否则会有刻度点未移动的问题
    addPlayRealtimeLister() {
      const that = this
      document.addEventListener('myTestEvent', e => {
        console.log(e)
        setTimeout(() => {
          const currentTime = that.$earth.viewer.clock.currentTime
          let TLstartTime = new Cesium.JulianDate()
          let TLstopTime = new Cesium.JulianDate()
          TLstartTime = Cesium.JulianDate.addDays(currentTime, -30, TLstartTime)
          TLstopTime = Cesium.JulianDate.addDays(currentTime, 30, TLstopTime)
          that.$earth.viewer.timeline.zoomTo(TLstartTime, TLstopTime)
          that.$earth.viewer.timeline.resize()
        }, 0)
      })
    },
    // 加载飞行轨迹
    loadTargetPath(airLineData) {
      if (!this.$earth.airTargetHistory) {
        this.$earth.airTargetHistory = new GV.TargetHistory(this.$earth.viewer)
        this.$earth.airTargetHistory.smoothTrack = true
      }
      this.$earth.airTargetHistory.removeAll()

      let hasAirLine = false
      const airLineTimeArray = []
      airLineData.forEach(item => {
        if (item.rangeHeight) {
          hasAirLine = true
          const lineData = JSON.parse(item.rangeHeight)
          // const line = turf.lineString(lineData)
          // lineData = turf.bezierSpline(line).geometry.coordinates

          const airLineTime = new Date(item.startTime).getTime()
          // 暂时设置每个时间点为startTime + 1分钟
          airLineTimeArray.push(airLineTime)
          lineData.forEach((innerItem, i) => {
            // innerItem.push(0)
            innerItem.push(airLineTime + i * 10 * 1000)
          })
          const id = `plan_${item.id}`
          const tTarget = new GV.TargetItem(id, lineData[0][0], lineData[0][1], lineData[0][2], 0)
          tTarget.name = id
          tTarget.angle = Math.random() * 360
          const style = tTarget.style
          style.pointDisplayConditionn = new Cesium.DistanceDisplayCondition(60000000)
          style.labelDisplayCondition = new Cesium.DistanceDisplayCondition(6000, 600000)
          style.iconDisplayCondition = new Cesium.DistanceDisplayCondition(60000, 60000000)
          style.modelDisplayCondition = new Cesium.DistanceDisplayCondition(0, 600000)
          style.labeloffsetx = 10
          style.labeloffsety = -20
          style.iconSize = 32
          style.modelUrl = '/data/model/Cesium_Air.glb'
          style.iconUrl = '/data/model/003.png'
          style.color = 'white'
          this.$earth.airTargetHistory.addTargetHistory(tTarget, lineData)
        }
      })
      if (hasAirLine) {
        this.startTime = new Date(Math.min(...airLineTimeArray))
        this.endTime = new Date(Math.max(...airLineTimeArray) + 60 * 60 * 1000)

        this.$earth.airTargetHistory.setTimeSection(this.startTime, this.endTime)
        this.$earth.airTargetHistory.pointSize = 0
        this.$earth.airTargetHistory.lineColor = Cesium.Color.BLUE
        const that = this
        // 设置时间轴为计划所在刻度
        setTimeout(() => {
          const currentTime = that.$earth.viewer.clock.currentTime

          console.log(Cesium.JulianDate.toDate(currentTime))
          let TLstartTime = new Cesium.JulianDate()
          let TLstopTime = new Cesium.JulianDate()

          TLstartTime = Cesium.JulianDate.addDays(currentTime, -30, TLstartTime)
          TLstopTime = Cesium.JulianDate.addDays(currentTime, 30, TLstopTime)

          that.$earth.viewer.timeline.zoomTo(TLstartTime, TLstopTime)
        }, 0)
      } else {
        Message({
          message: '飞行计划暂无航线数据',
          type: 'error',
          duration: 2000
        })
      }
    },
    // 移除飞行轨迹
    removeTargetPath() {
      if (this.$earth.airTargetHistory) {
        this.$earth.airTargetHistory.removeAll()
      }
    },
    // 设置时间轴为计划所在时间段
    setTimeLine() {
      if (!this.startTime) {
        Message({
          message: '暂无加载飞行计划',
          type: 'error',
          duration: 2000
        })
      } else {
        const that = this
        setTimeout(() => {
          // 设置系统时间为计划开始时间
          // const cTime = new Date('2014/03/20 14:20:05')
          // const cJulianDate = new Cesium.JulianDate()
          // Cesium.JulianDate.fromDate(cTime, cJulianDate)
          // that.$earth.viewer.clock.currentTime = Cesium.JulianDate.fromDate(cTime, cJulianDate)
          // const currentTime = that.$earth.viewer.clock.currentTime

          const planJulianDate = new Cesium.JulianDate()
          Cesium.JulianDate.fromDate(that.startTime, planJulianDate)
          let TLstartTime = new Cesium.JulianDate()
          let TLstopTime = new Cesium.JulianDate()
          TLstartTime = Cesium.JulianDate.addDays(planJulianDate, -30, TLstartTime)
          TLstopTime = Cesium.JulianDate.addDays(planJulianDate, 30, TLstopTime)
          that.$earth.viewer.timeline.zoomTo(TLstartTime, TLstopTime)
        }, 0)
      }
    },
    getRandom(max, min) {
      return Math.round((Math.random() * (max - min) + min) * 10) / 10
    }
  }
}
</script>

<style lang="scss" scoped>
.slide-fade-enter-active {
  transition: all 0.4s ease;
}
.slide-fade-leave-active {
  transition: all 0.4s ease;
}
.slide-fade-enter, .slide-fade-leave-to
/* .slide-fade-leave-active for below version 2.1.8 */ {
  transform: translateX(10px);
  opacity: 0;
}
.planManage-main {
  .btn-content {
    position: absolute;
    top: 96px;
    left: 20px;
    width: 40px;
    .btn-content-img {
      width: 40px;
      height: 40px;
      margin-bottom: 30px;
      cursor: pointer;
    }
  }
  .plan-main {
    position: absolute;
    top: 100px;
    left: 80px;
    width: 555px;
    height: 650px;
    background: rgba(5, 34, 74, 0.5);
    border-radius: 4px;
    border: 1px solid rgba(8, 75, 108, 1);
    .plan-main-title {
      .shrink-btn {
        cursor: pointer;
        position: absolute;
        top: 16px;
        right: 20px;
        width: 12px;
        height: 13px;
        transform: rotate(180deg);
      }
      .title {
        font-size: 16px;
        color: #62adf8;
        text-align: left;
        margin: 10px 0px 15px 16px;
      }
      .separator {
        height: 1px;
        border-right: 120px solid #fff;
        border-left: 435px solid #17336b;
      }
    }
    .current-time {
      color: #62adf8;
      text-align: center;
      margin: 14px;
      font-size: 14px;
      .current-time-title {
        margin-bottom: 5px;
      }
    }
    .querySearch {
      position: relative;
      margin: 20px 80px;

      /deep/ .el-input {
        margin-bottom: 10px;
        .el-input__inner {
          background: transparent;
        }
      }
      /deep/ .el-date-editor {
        display: block;
        .el-input__inner {
          color: #fff;
        }
      }
      .search-btn {
        position: absolute;
        right: 20px;
        top: 20px;
      }
    }
    .plan-main-table {
      margin: 10px;
      /deep/ .el-table {
        background-color: transparent;
        color: #fff;
        margin: 5px;
        width: 100%;

        th,
        tr {
          background-color: transparent;
        }
        thead {
          color: #fff;
        }
        .el-table__body-wrapper {
          height: 340px;
          @include scrollbar-custom;
        }
      }
    }
    /deep/ .el-table--enable-row-hover .el-table__body tr:hover > td {
      background: rgba(5, 34, 74, 0.6) !important;
    }
    .render-btn {
      position: absolute;
      bottom: 5px;
      right: 10px;
    }
    .remove-btn {
      position: absolute;
      bottom: 5px;
      right: 150px;
    }
  }
  .btn {
    position: absolute;
    bottom: 28px;
    left: 170px;
    width: 30px;
    background-color: #384350;
    border-radius: 5px;

    cursor: pointer;
  }
}
</style>
